<?php

namespace App\Http\Controllers\Client\Course;

use App\Http\Controllers\ClientController;
use App\Models\WechatPay;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Redis;

class CoursePayController extends ClientController
{

    /**
     * @api {post} /api/client/course/pay 创建订单接口
     *
     * @apiVersion 0.1.0
     * @apiName 创建订单接口
     * @apiGroup course
     * @apiDescription 创建微信订单
     *
     * @apiParam {Number} type      订单类型    （必填）    1：会员，2：课程
     * @apiParam {Number} outer_id  会员/订单id （必填）
     *
     * @apiSuccess {int}      code  接口返回正误标志,0为成功,其他为失败.
     * @apiSuccess {String}   msg   接口返回信息
     * @apiSuccess {Object[]} data  接口返回data.
     *
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "创建成功"
     *       "data": [...]
     *     }
     */
    public function index()
    {

        $all = $this->all;

//        // 测试不允许购买
//        if(env("APP_ENV") !== "production"){
//            return $this->setReturnJson(-1,'测试公众号不允许购买');
//        }

        //验证
        try{
            // 验证参数
            if(!isset($all['type'])){
                throw new \Exception('缺少参数:type');
            }
            if(!in_array($all['type'], [1, 2])){
                throw new \Exception('错误的参数:type');
            }
            if(!isset($all['outer_id'])){
                throw new \Exception('缺少参数:outer_id');
            }

            // 验证数据库是否保存了用户的手机号，如果没有，验证redis的code和phone并保存

            $has_phone = DB::table('lottery_users')->where('we_id',$this->we_id)->value('phone');
            // 如果未传验证码且未保存手机,不允许购买会员
            if(!$has_phone && !isset($all['code'])){
                return $this->setReturnJson(-1, '未验证手机号,不允许购买服务');
            }

            if(isset($all['code'])) { // 如果传了验证码，验证验证码
                if ($all['code'] != Redis::hget('message_code_' . $this->we_id, 'code')) {
                    return $this->setReturnJson(-1, '验证码错误');
                } else {
                    $phone = Redis::hget('message_code_' . $this->we_id, 'phone');
                    // 如果验证了新的手机号，保存手机号
                    if($phone){
                        DB::table('lottery_users')->where('we_id',$this->we_id)->update(['phone'=>$phone]);
                    }
                    // 删除验证码信息
                    Redis::del('message_code_' . $this->we_id);
                }
            }

            // 实例化微信支付订单类
            $pay = new WechatPay(
                $this->we_id,
                $this->openid,
                $all['type'],
                $all['outer_id']
            );

        }catch (\Exception $e){
            Log::error(CoursePayController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'订单生成失败');
        }


        // 生成订单操作
        try{
            DB::beginTransaction();


            // 查询业务信息
            $order_message = $pay->getOrderMessage();

            // 创建系统订单
            $message = $pay->createOrder($order_message);
            switch ($message){
                case 1:
                    throw new \Exception('订单数量超限');
                    break;
                case 2:
                    DB::rollBack();
                    return $this->setReturnJson(-1,'不允许续费低级会员');
                    break;
                case 3:
                    DB::rollBack();
                    return $this->setReturnJson(-1,'课程已购买,请不要重复购买课程');
                    break;
                case 4:
                    DB::commit();
                    return $this->setReturnJson(-1,'会员已购买完成，请刷新重试');
                    break;
                case 5:
                    DB::commit();
                    return $this->setReturnJson(-1,'课程已购买，请刷新重试');
                    break;
            }
            // 创建微信订单
            $prepay_id = $pay->createWechatOrder($message);
            // 返回微信请求
            $result = $pay->sdkConfig($prepay_id);


            DB::commit();
            return $this->setReturnJson(0,'订单生成成功',$result);

        }catch (\Exception $e){
            DB::rollBack();
            Log::error(CoursePayController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'订单生成失败');
        }
    }

}